package mail

import (
	"fmt"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/common"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

// QueryMailInfo 获取邮箱信息
// @Summary 获取邮箱数据信息
// @Description 获取邮箱数据信息
// @Tags API.mail
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Success 200 {object} response.TResponse{data=vo.MailVO}
// @Failure 400 {object} response.TResponse{data=interface{}}
// @Router /api/mail/info [get]
func (m *mailController) QueryMailInfo(c *gin.Context) {
	mail := common.Get().Mail
	fmt.Println("mail info", mail)
	response.Success(c, "获取邮箱信息成功", gin.H{
		"host": mail.Host,
		"pass": mail.Pass,
		"port": mail.Port,
		"to":   mail.To,
		"user": mail.User,
	})
}

// UpdateMailInfo 更新邮箱信息
// @Summary 更新邮箱数据信息
// @Description 更新邮箱数据信息
// @Tags API.mail
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Param host formData string true "邮箱服务器"
// @Param port formData string true "端口"
// @Param user formData string true "发件人邮箱"
// @Param pass formData string true "发件人密码"
// @Param to formData string true "收件人邮箱地址，多个用,分割"
// @Success 200 {object} response.TResponse{data=vo.MailVO}
// @Failure 400 {object} response.TResponse{data=interface{}}
// @Router /api/mail/info [patch]
func (m *mailController) UpdateMailInfo(c *gin.Context) {
	var mailReq QO.EmailReqQO
	if err := c.ShouldBind(&mailReq); err != nil {
		response.Fail(c, code.ParamBindError, code.Text(code.ParamBindError), gin.H{"realErr": err})
		return
	}

	err := m.MailService.SendEmailService(c, mailReq)

	// 设置
	viper.Set("mail.host", mailReq.Host)
	viper.Set("mail.port", mailReq.Port)
	viper.Set("mail.user", mailReq.User)
	//viper.Set("mail.pass", mailReq.Pass)
	viper.Set("mail.to", mailReq.To)
	writeErr := viper.WriteConfig()
	if writeErr != nil {
		response.Fail(c, code.WriteConfigError, code.Text(code.WriteConfigError), gin.H{"realErr": err})
		return
	}
	if err == nil {
		response.Success(c, "发送信息成功", gin.H{})
	}
}
